package com.example.studyPlatform.controller.api;

import com.example.studyPlatform.bean.Post;
import com.example.studyPlatform.mapper.PostMapper;
import com.example.studyPlatform.service.protocol.MarkdownService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.example.studyPlatform.config.RoutingConstant.ARTICLE;
import static com.example.studyPlatform.config.RoutingConstant.PUBLIC_PATH;

@Component
@AllArgsConstructor
public class ContentApi {
    MarkdownService markdownService;
    PostMapper postMapper;

    //@CrossOrigin(origins = "*", maxAge = 3600)
    @PostMapping(value = ARTICLE + "/render", produces = {MediaType.TEXT_PLAIN_VALUE})
    @ResponseBody
    public String render(String content) {
        return tableRender(markdownService.markdownToHTML(content));
    }

    @ResponseBody
    @PostMapping(value = ARTICLE + "/content/{id:[0-9]+}", produces = {MediaType.APPLICATION_JSON_VALUE})
    public Post content(@PathVariable("id") int id) {
        // TODO 判断权限
        Post post = postMapper.getPostById(id);
        if (post != null) {
            post.setContent(render(post.getContent()));
            if (StringUtils.isBlank(post.getUrl())) {
                post.setUrl(PUBLIC_PATH + ARTICLE + post.getId());
            }
        }
        return post;
    }

    // 渲染表格NLP core
    public String tableRender(String markdown) {
        Pattern wp = Pattern.compile("(\\s*\\|.*\\|\\s*\\n)+(\\s*\\|.*\\|\\s*)", Pattern.MULTILINE);
        Matcher matcher = wp.matcher(markdown);
        StringBuffer md = new StringBuffer();
        int last = 0;
        while (matcher.find()) {
            int s = matcher.start(), e = matcher.end();
            String table = markdown.substring(s, e).trim();
            String[] tr = table.split("\\n");

            String[] aligns = getAligns(tr[1]);
            tr[0] = md2htmlTable(tr[0], "th", aligns);
            for (int i = 2; i < tr.length; i++) {
                tr[i] = md2htmlTable(tr[i], "td", aligns);
            }
            StringBuffer sb = new StringBuffer();
            sb.append("<div class=\"table-wrapper\"><table><thead><tr>");
            sb.append(tr[0]).append("</tr></thead><tbody>");
            for (int i = 2; i < tr.length; i++) {
                sb.append("<tr>").append(tr[i]).append("</tr>");
            }
            sb.append("</tbody></table></div>");
            md.append(markdown.substring(last, s)).append(sb.toString());
            last = e;
        }
        md.append(markdown.substring(last));
        return md.toString();
    }

    String replace(String s, int start, int end, String t) {
        return s.substring(0, start) + t + s.substring(end);
    }

    String md2htmlTable(String md, String tag, String[] aligns) {
        StringBuffer sb = new StringBuffer();
        int state = 0;
        md = md.replaceAll("(^\\s*\\|)|(\\|\\s*$)", "");
        String[] cells = md.split("\\|");
        for (int i = 0; i < cells.length; i++) {
            sb.append("<" + tag);
            if (!StringUtils.isBlank(aligns[i])) {
                sb.append(" style=\"float:%\"".replace("%", aligns[i]));
            }
            sb.append(">");
            sb.append(cells[i]);
            sb.append("</" + tag + ">");
        }
        return sb.toString();
    }

    String[] getAligns(String s) {
        String t = "\\s*-+\\s*";
        return s.replaceAll("(^\\s*\\|)|(\\|\\s*$)", "")
                .replaceAll(":" + t + ":", "center")
                .replaceAll(":" + t, "left")
                .replaceAll(t + ":", "right")
                .replaceAll(t, "none")
                .split("\\|");
    }
}
